import axios from "axios";
import browser from "../common/browser";
import { Message } from "element-ui";
import store from "@/store";
import { SET_LOADING } from "@/store/mutation-type";
// import Qs from 'qs'
// 创建 axios 实例
let http = axios.create({
  // headers: {'Content-Type': 'application/json'},
  timeout: 60000,
});
// 设置 post、put 默认 Content-Type
http.defaults.headers.post["Content-Type"] = "application/json";

// 添加请求拦截器
http.interceptors.request.use(
  (config) => {
    store.commit(SET_LOADING, true);
    if (localStorage.getItem("fn_token")) {
      config.headers.Authorization = localStorage.getItem("fn_token");
    }
    const userInfo = localStorage.getItem("fn_userInfo")
      ? JSON.parse(localStorage.getItem("fn_userInfo"))
      : null;
    const local_user = localStorage.getItem("fn_local_user")
      ? JSON.parse(localStorage.getItem("fn_local_user"))
      : null;
    if (config.method === "post") {
      // config.data = JSON.stringify(config.data)
      let data = JSON.parse(config.data);
      // 判断是否日志上报接口
      if (config.url.indexOf("/track") != -1) {
        let now = Date.now();
        let balance = JSON.parse(localStorage.getItem("fn_balance"));
        // 判断是否用户数据接口
        if (config.url.indexOf("user_analysis") != -1) {
          config.data = JSON.stringify({
            source: 2, //数据来源 2.pc，3.m端
            version: "3.0.0",
            channelId: "2000001001", //渠道号
            createTime: now, //上报时间(时间戳)
            isNew: userInfo
              ? balance
                ? balance.isNew
                : 1
              : local_user
              ? now > local_user.todayTime
                ? 0
                : 1
              : 1, //是否新用户：0否；1是
            isVip: userInfo ? (balance ? balance.isVip : 0) : 0, //是否会员：0否；1是
            deviceId: local_user ? local_user.userId : "", //设备id local生成随机ID
            userId: userInfo ? userInfo.authorId : "", //用户id
            isVisitor: userInfo ? 0 : 1, //是否游客：0否；1是
            ...data,
          });
        } else {
          config.data = JSON.stringify({
            source: 2, //数据来源 2.pc，3.m端
            version: "3.0.0",
            channelId: "2000001001", //渠道号
            createTime: now, //上报时间(时间戳)
            userIdentity: userInfo
              ? balance
                ? balance.isNew
                  ? balance.isVip
                    ? 6
                    : 5
                  : balance.isVip
                  ? 8
                  : 7
                : 5
              : local_user
              ? now > local_user.todayTime
                ? 3
                : 1
              : 1, //用户身份 待修改
            deviceId: local_user ? local_user.userId : "", //设备id local生成随机ID
            userId: userInfo ? userInfo.authorId : "", //用户id
            ...data,
          });
        }
      } else {
        config.data = JSON.stringify({
          appVer: "3.0.0",
          channelId: "2000001001", //渠道号
          userId: userInfo
            ? userInfo.authorId
            : local_user
            ? local_user.userId
            : "", //用户ID
          userPort: browser.isAndroid ? 0 : 1,
          ...data,
        });
      }
    } else if (config.method === "get" || config.method === "delete") {
      // 判断是否日志上报接口
      if (config.url.indexOf("/track") != -1) {
        let now = Date.now();
        let balance = JSON.parse(localStorage.getItem("fn_balance"));
        // 判断是否用户数据接口
        if (config.url.indexOf("user_analysis") != -1) {
          config.params = {
            APIVersion: "0.6.0",
            source: 2, //数据来源 2.pc，3.m端
            version: "3.0.0",
            channelId: "2000001001", //渠道号
            createTime: now, //上报时间(时间戳)
            isNew: userInfo
              ? balance
                ? balance.isNew
                : 1
              : local_user
              ? now > local_user.todayTime
                ? 0
                : 1
              : 1, //是否新用户：0否；1是
            isVip: userInfo ? (balance ? balance.isVip : 0) : 0, //是否会员：0否；1是
            deviceId: local_user ? local_user.userId : "", //设备id local生成随机ID
            userId: userInfo ? userInfo.authorId : "", //用户id
            isVisitor: userInfo ? 0 : 1, //是否游客：0否；1是
            ...config.params,
          };
        } else {
          config.params = {
            APIVersion: "0.6.0",
            source: 2, //数据来源 2.pc，3.m端
            version: "3.0.0",
            channelId: "2000001001", //渠道号
            createTime: now, //上报时间(时间戳)
            userIdentity: userInfo
              ? balance
                ? balance.isNew
                  ? balance.isVip
                    ? 6
                    : 5
                  : balance.isVip
                  ? 8
                  : 7
                : 5
              : local_user
              ? now > local_user.todayTime
                ? 3
                : 1
              : 1, //用户身份 待修改
            deviceId: local_user ? local_user.userId : "", //设备id local生成随机ID
            userId: userInfo ? userInfo.authorId : "", //用户id
            ...config.params,
          };
        }
      } else {
        config.params = {
          appVer: "3.0.0",
          channelId: "2000001001", //渠道号
          userId: userInfo
            ? userInfo.authorId
            : local_user
            ? local_user.userId
            : "", //用户ID
          userPort: browser.isAndroid ? 0 : 1,
          ...config.params,
        };
      }
    }
    // 请求发送前进行处理
    return config;
  },
  (error) => {
    // 请求错误处理
    return Promise.reject(error);
  }
);

// 添加响应拦截器
http.interceptors.response.use(
  (response) => {
    store.commit(SET_LOADING, false);
    let { data } = response;
    return data;
  },
  (error) => {
    const errcode = error.data.msg * 1;
    if (errcode === 40003 || errcode === 40004 || errcode === 40005) {
      localStorage.setItem("fn_token", "");
      localStorage.setItem("fn_userInfo", null);
      Message.error({
        message: "Login failed. Please log in again",
        position: "top",
      });
    }

    let info = {};
    let { status, statusText, data } = error.response;
    if (!error.response) {
      info = {
        code: 5000,
        msg: "Network Error",
      };
    } else {
      // 此处整理错误信息格式
      info = {
        code: status,
        data: data,
        msg: statusText,
      };
    }
    return Promise.reject(info);
  }
);

/**
 * 创建统一封装过的 axios 实例
 * @return {AxiosInstance}
 */
export default function () {
  return http;
}
